<template>
	<view class="div-upload">
		<uv-upload :fileList="fileList" deletable @afterRead="upfiles" @delete="deletePic" multiple
			:previewFullImage="false" :maxCount="maxCount" width="160rpx" height="160rpx" :accept="props.accept">
		</uv-upload>
	</view>
</template>

<script lang="ts" setup>
	import { toast } from '@/uni_modules/uv-ui-tools/libs/function/index.js';
	import { onReady, onShow, onLoad } from '@dcloudio/uni-app';
	import { ref, watch, defineProps } from 'vue';
	import { http, apiPath, http_upload } from '@/common/http/index';

	// 使用defineProps定义接收的props  
	const props = defineProps({
		accept: {
			type: String,
			default: 'image'
		}, maxCount: {
			type: Number,
			default: 6
		}
	});

	const fileList = ref([]) as any
	const uploading = ref(false)

	const deletePic = (event : any) => {
		fileList.value.splice(event.index, 1);
	};
	const upfiles = async (event : any) => {
		console.log('event.name', event.name)
		// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = fileList.value.length;

		lists.map((item : any) => {

			fileList.value.push({
				...item,
				status: 'uploading',
				message: '上传中'
			});
		});

		// let that = this;

		// http.post(`/shop/bonus/send`, params).then((res : any) => {
		// 	console.log('res.data', res.data.id)

		// 	pay(res.data.id)
		// }).catch(() => {
		// 	setTimeout(() => {
		// 		loading.value = false;
		// 	}, 2000);
		// })

		for (let i = 0; i < lists.length; i++) {
			console.log('fileList.value', lists[i].url)
			await http_upload({ url: '/api/v1/upload/local/image', filePath: lists[i].url }).then((res : any) => {
				console.log('res.data', res.data)
				let item = fileList.value[fileListLen];
				fileList.value.splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: 'success',
						message: '',
						url: res.data
					})
				);
				fileListLen++;

			}).catch(err => {
				console.log('err', err);
				toast('上传失败');
				fileList.value.splice(event.index, 1);
			})

		}
	};
	const set_imgs = (imgs : any) => {
		fileList.value = imgs.map((item : any) => {
			console.log(item)
			let obj = {
				url: item, // 预览图片的地址
				thumb: item
			}
			return obj
		})
	};
	const get_imgs = () => {


		let images = fileList.value.flatMap((item) => {
			return item.url;
		});
		return images;
	};

	defineExpose({ get_imgs, set_imgs });
</script>

<style lang="scss" scoped>
	:deep(.uv-upload__button) {
		background: #fff !important;
	}
</style>